#!/bin/sh /etc/rc.common

START=99
USE_PROCD=1

DNSMASQ_UCI_CONFIG="$(uci -q show "dhcp.@dnsmasq[0]" | awk 'NR==1 {split($0, conf, /[.=]/); print conf[2]}')"
if [ -f "/tmp/etc/dnsmasq.conf.$DNSMASQ_UCI_CONFIG" ];then
	DNSMASQ_VLMCSD="$(awk -F '=' '/^conf-dir=/ {print $2}' "/tmp/etc/dnsmasq.conf.$DNSMASQ_UCI_CONFIG")/dnsmasq-vlmcsd.conf"
else
	DNSMASQ_VLMCSD="/tmp/dnsmasq.d/dnsmasq-vlmcsd.conf"
fi

start_service() {
	local enabled auto_activate internet_access

	config_load "vlmcsd"
	config_get_bool enabled "config" "enabled" "0"
	config_get_bool auto_activate "config" "auto_activate" "0"
	config_get_bool internet_access "config" "internet_access" "0"

	[ "$enabled" -eq "1" ] || return 1

	if [ "$auto_activate" -eq "1" ];then
		hostname="$(uci get system.@system[0].hostname)"
		echo "srv-host=_vlmcs._tcp,$hostname,1688,0,100" > "$DNSMASQ_VLMCSD"
		/etc/init.d/dnsmasq restart 2>"/dev/null"
	fi

	procd_open_instance "vlmcsd"
	procd_set_param command /usr/bin/vlmcsd
	procd_append_param command -D
	procd_append_param command -i "/etc/vlmcsd.ini"
	procd_append_param command -L "[::]:1688"

	procd_set_param file /etc/vlmcsd.ini
	procd_set_param stdout 1
	procd_set_param stderr 1
	procd_set_param respawn

	if [ "$internet_access" -eq "1" ];then
		procd_open_data
		json_add_array firewall
			json_add_object ""
			json_add_string type rule
			json_add_string name "Allow-vlmcsd-tcp"
			json_add_string proto "tcp"
			json_add_string src "wan"
			json_add_string dest_port "1688"
			json_add_string target "ACCEPT"
			json_close_object
		json_close_array
		procd_close_data
	fi

	procd_close_instance
}

service_started() {
	procd_set_config_changed firewall
}

stop_service() {
	rm -f "$DNSMASQ_VLMCSD"
	/etc/init.d/dnsmasq restart 2>"/dev/null"
}

service_stopped() {
	procd_set_config_changed firewall
}

reload_service() {
	stop
	start
}

service_triggers() {
	procd_add_reload_trigger vlmcsd
}
